#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging
from utility import tools
from command.handler import gwys_handler
from command.handler import dict_handler

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)

class HighRiskAssEvaListAPI(Resource):
    """
    高危评估列表查询
    :request: post
    :param status: 状态 0 审核中 1已审核
    :param gwColorCode: 高危颜色
    :param pgsjStartDate: 评估开始时间
    :param pgsjEndDate: 评估结束时间
    :param searchText: 搜索字符串
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件 status
            archives_ids=[]
            query_ = []
            if params.get('status'): # 档案状态
                query_t_ = []
                query_t_.append(('state', '=', params.get('status')))  #档案状态  
                assess_record = odoo.env['risk.assess.record'].search_read(query_t_,['archives_id'])
                if assess_record:
                    archives_ids = [archives['archives_id'][0]  for archives in assess_record]
                    #query_.append(('archives_id', 'in', archives_ids))      
            if params.get('pgsjStartDate'): #评估开始时间
                query_t_ = []
                query_t_.append(('pg_sj', '>=', params.get('pgsjStartDate')))
                score_record = odoo.env['risk.score.record'].search_read(query_t_,['archives_id'])
                if score_record:
                    archives_ids_ = [archives['archives_id'][0]  for archives in score_record]
                    if archives_ids:
                        archives_ids=archives_ids.intersection(archives_ids_)
                    else:
                        archives_ids += archives_ids_        
            if params.get('pgsjEndDate'): # 评估结束时间
                query_t_ = []
                query_t_.append(('pg_sj', '<=', params.get('pgsjEndDate')))
                score_record = odoo.env['risk.score.record'].search_read(query_t_,['archives_id'])
                if score_record:
                    archives_ids_ = [archives['archives_id'][0]  for archives in score_record]
                    if archives_ids:
                        archives_ids=archives_ids.intersection(archives_ids_)
                    else:
                        archives_ids += archives_ids_
            if archives_ids:
               query_.append(('id', 'in', archives_ids))       
            if params.get('searchText'): # 搜索字符串
                query_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名  
                query_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码 
            if params.get('gwColorCode'):
                query_.append(('max_gwys', '=', int(params.get('gwColorCode'))))            
            fields = [
                    'mq_xm','mq_cz_address','mq_mz',
                    'mq_age','max_gwys','yz','mq_sfz','id'
                    ]    
            res_archives = odoo.env['res.archives'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = {'rows':[],'total':0}
            data_['total'] = odoo.env['res.archives'].search_count(query_) 
            if res_archives:
                for  res_archives_ in res_archives:
                    query_t_=[('archives_id', '=', res_archives_['id'])]
                    assess_record = odoo.env['risk.assess.record'].search_read(query_t_,['pgd_code','state'])
                    score_record = odoo.env['risk.score.record'].search_read(query_t_,['pg_jg','pg_ys'])
                    data_tmp={
                        'pgdh': assess_record[0]['pgd_code'] if assess_record else '',
                        'mqXm': res_archives_['mq_xm'],
                        'mqZz': res_archives_['mq_cz_address'],
                        'mqMz': res_archives_['mq_mz'],
                        'mqAge': res_archives_['mq_age'],
                        'yz': res_archives_['yz'],
                        'gwColorCode': res_archives_['max_gwys'],
                        'idCard': res_archives_['mq_sfz'],
                        'bgjgName':score_record[0]['pg_jg'][-1] if score_record else '',
                        'bgrName':score_record[0]['pg_ys'][-1] if score_record else '',
                        'status':assess_record[0]['state'] if assess_record else '',
                        'id':res_archives_['id']
                    }
                    data_['rows'].append(data_tmp)   
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class HighRiskAssEvaQueryByIdAPI(Resource):
    """
    根据高危评估单ID查询展开详情
    :request: get
    :param id: id
    :returns: json string
    """
    def get(self):
        try:
            #  参数校验
            odoo = OdooManager().get_instance()
            params = request.values
            req_params = ['id']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_=[('archives_id', '=', int(params.get('id')))]
            fields=['gwpg_gxpg','zdzdyj_zd_text','cl_zz','gwpg_gwys']
            diagnostics = odoo.env['inspection.diagnostic'].search_read(query_,fields)
            data_ = {}
            if diagnostics:
                diagnostics=diagnostics[0]
                data_ = {
                    'gwys': gwys_handler.get_gwys_value(diagnostics['gwpg_gxpg']),
                    'gwColor': dict_handler.get_dict_value(diagnostics['gwpg_gwys'],'ck_gwys'),
                    'gwColorCode': diagnostics['gwpg_gwys'],
                    'zdcl': dict_handler.get_dict_value(diagnostics['cl_zz'],'ck_ty_sf'),
                    'zdyj': diagnostics['zdzdyj_zd_text']
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class HighRiskAssEvaExamineAPI(Resource):
    """
    根据高危评估单ID审核
    :request: put
    :param id: id
    :returns: json string
    """
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            # 参数校验
            req_params = ['id']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            query_ = [('archives_id', '=', int(params.get('id')))]
            record = odoo.env['risk_assess_record'].search(query_)
            if not record:
                return jsonify({'code': 40005, 'msg': error_code[40005]})
            data_ = {
                'state': 'done',
            }
            data_ = odoo.env['risk_assess_record'].write(record,data_)
            create_event = event_type.OperationLogEvent('高危评估单ID审核', 'id:{}'.format(params.get('id')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'id': data_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

